<style lang="less" scoped>
/deep/.el-dialog--center .el-dialog__body {
  padding: 22px 30px 55px;
}

/deep/ .el-table .cell {
  font-weight: bold;
}

/deep/.el-form-item__label {
  padding-right: 0;
}

/deep/.el-tabs__nav-wrap::after {
  background-color: #FFF;
}

.btnBox {

  width: 70px;
  height: 32px;
  background-color: #fff;
  // border: 1px solid #DCDFE6;
  padding: 0;
}


.transpondContent {
  ::v-deep .el-table .DisableSelection .cell .el-checkbox__inner {
    display: none;
    position: relative;
  }

  ::v-deep .el-table .DisableSelection .cell:before {
    content: "";
    position: absolute;
  }

  // /deep/.el-table__body-wrapper {
  //   &::-webkit-scrollbar {
  //     // 整个滚动条
  //     width: 0; // 纵向滚动条的宽度
  //     background: rgba(213, 215, 220, 0.3);
  //     border: none;
  //     height: 0;
  //   }

  //   &::-webkit-scrollbar-track {
  //     // 滚动条轨道
  //     border: none;
  //   }
  // }
  /deep/ .el-progress-bar__outer {
    width: 100%;
  }

}

.font_red {
  color: red !important;
}
</style>
<template>
  <div class="transpondContent">
    <el-dialog v-el-drag-dialog id="transpondImg" title="影像转发" :visible.sync="TranspondImgShow"
      :before-close="TranspondImgClose" width="900px" top="3%" center>
      <div class="of">
        <el-form class="of" label-position="right">
          <div class="mb20"> <strong> 选择目标节点</strong></div>
          <div style="width: 840px;">

            <el-table :data="routingNodes" border max-height="160px" :header-cell-class-name="cellClass"
              :header-cell-style="{ background: '#F5F5F5', color: '#333' }" highlight-current-row
              header-row-class-name="strong" @selection-change="tableSelectionChanged" ref="nodeTab">
              <el-table-column fixed="left" type="selection" :reserve-selection="true"
                :selectable="() => { return imgSending === 0 }"></el-table-column>
              <common-table :propData="upPropData"></common-table>
            </el-table>
            <!--  -->
            <div class=" mt10 mb10 mr10 w100" v-show="imgSending === 1">
              <div>目标节点：{{ routingnode.node_name }} （{{ completeCount }}/{{ totalCount }}） </div>
              <el-progress class="w100" :percentage="percentage"></el-progress>

            </div>
            <div class="mt10 mb10 fr">
              <el-button plain class="btnBox" type="primary" @click="TranspondImgClose" size="medium">
                {{ cancelTitle }}</el-button>
              <el-button type="primary" @click="sendFn" size="medium" :disabled="selectedNodes.length
                === 0 || imgSending !== 0">发送</el-button>
            </div>
          </div>

        </el-form>
        <div style="width: 840px;" class="mt10" v-if="successData.length > 0">
          <div class="h40 mb10 mt10"
            style="background-color: rgba(28, 181, 74, 0.1); border-radius: 5px;  text-align: center; line-height: 40px;">
            <div class="clr_green h40 f14"><i class="iconfont mr5">&#xe6aba;</i>发送成功</div>
          </div>
          <el-table :data="successData" max-height="160px" border
            :header-cell-style="{ background: '#F5F5F5', color: '#333' }" highlight-current-row
            header-row-class-name="strong">
            <el-table-column label="序" width="50" fixed="left">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <common-table :propData="successPropData"></common-table>
          </el-table>
        </div>
        <div style="width: 840px;" class="mt10" v-if="failData.length > 0">
          <div class="h40 mb10"
            style="background-color: rgba(255, 111, 111, 0.1); border-radius: 5px;  text-align: center; line-height: 40px;">
            <div class="clr_red h40 f14"><i class="iconfont mr5">&#xe6ed;</i>发送失败</div>
          </div>
          <el-table :data="failData" max-height="160px" border
            :header-cell-style="{ background: '#F5F5F5', color: '#333' }" highlight-current-row
            header-row-class-name="strong">
            <el-table-column label="序" width="50" fixed="left">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>

            <common-table :propData="propData"></common-table>
            <el-table-column fixed="right" label="失败原因" width="200" align="center">

              <template slot-scope="scope">
                <span class="clr_red">{{
                  scope.row.error_msg
                }}</span>
              </template>


            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>


    <!-- 取消导入影像 -->
    <el-dialog class="cancelSendDialog" v-if="cancelSendShow" title="提示" :visible.sync="cancelSendShow" width="380px"
      top="31vh" :before-close="() => { cancelSendShow = false }">
      <div class="pt20 pl20 pb20 bbd h20">
        <!-- <div class="clr_warn mb10">
          <i class="iconfont clr_warn" style="font-size: 20px;">&#xe680;</i>
          <span class="f16 ml5">
            重新导入
          </span>
        </div> -->
        <div class="pb10 f16"><i class="iconfont clr_warn mr5"
            style="font-size: 18px;">&#xe680;</i><span>确定取消本次影像发送？</span></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelSendShow = false">取消</el-button>
        <el-button size="small" type="primary" @click="cancelSendSure">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CommonTable from '@/components/common/CommonTable'
// import SearchTime from '../../common/SearchTime'
// import SendImg from '@/components/pacs/commonDialog/SendImg' // 影像发送 弹框

export default {
  data() {
    return {
      cancelSendShow: false,
      currentImageData: {},
      currentAetModel: {
        name: 'AET1',
        patient_id: '289692',
        exam_id: 'CT-020192',
        sers: 8,
        current: 1,
      },
      elDialogHeight: '0px',
      failureHeight: 0,
      imgSending: 0, //0初始状态 1发送中 2发送已完成
      routingnode: '',
      routingNodes: [],
      selectedNodes: [],
      percentage: 0,
      activeName: '-1',
      initTime: [],
      showErrorList: false,
      searchStartTime: '',
      searchEndTime: '',
      clearTime: false,
      upPropData: [
        {
          prop: 'system_name',
          label: '系统名称'
        },
        {
          prop: 'institution_name',
          label: '机构名称'
        },
        {
          prop: 'node_name',
          label: '节点描述',
          width: 200
        },
        {
          prop: 'node_host',
          label: '节点地址',
          width: 160
        },
        {
          prop: 'node_aet',
          label: '应用标识',
          width: 100
        },
        {
          prop: 'node_port',
          label: '服务端口',
          width: 100
        }
      ],
      propData: [
        {
          prop: 'node_host',
          label: '目标节点地址'
        },
        {
          prop: 'node_aet',
          label: '目标节点标识'
        },
        {
          prop: 'patient_id',
          label: '患者编号',
          width: 120
        },
        {
          prop: 'accession_number',
          label: '检查编号',
          width: 160
        },
        // {
        //   prop: 'error_msg',
        //   label: '失败原因',
        //   width: 200
        // }
      ], // table表格原始表头数据
      successPropData: [
        {
          prop: 'node_host',
          label: '目标节点地址'
        },
        {
          prop: 'node_aet',
          label: '目标节点标识'
        },
        {
          prop: 'patient_id',
          label: '患者编号',
          width: 120
        },
        {
          prop: 'accession_number',
          label: '检查编号',
          width: 160
        }
      ],
      sendImgShow: false,
      timeId: null,
      completeCount: 0,
      failData: [],
      successData: [],
      totalCount: 0,
      currentData: '',
      cancelTitle: '关闭',
      canceled: false,
      msgCount: 0,
      refusedReasons: ['无法访问，连接被拒绝', 'DICOM通信请求被拒绝'],
    }
  },
  props: ['TranspondImgShow', 'TranspondDatas'],
  watch: {
    imgSending(val) {
      this.cancelTitle = (val === 1) ? '取消' : '关闭'

    },
    TranspondImgShow(val) {
      if (val) {
        this.imgSending = 0
        this.closeSession()
        this.failData = []
        this.successData = []
        this.percentage = 0
        this.totalCount = 0
        this.completeCount = 0
        this.canceled = false
        this.timeId = null
      }
    }
  },
  computed: {

  },

  methods: {
    closeSession() {
      this.selectedNodes = []
      this.$nextTick(() => {
        this.$refs.nodeTab.clearSelection()
      })
    },
    cellClass() {
      return (this.imgSending !== 0) ? 'DisableSelection' : ''
    },
    // testForPercentage() {
    //   this.timer = setInterval(() => {
    //     if (this.percentage === 100) {
    //       clearInterval(this.timer)
    //     } else {
    //       this.percentage = this.percentage + 10
    //     }
    //   }, 1000);
    // },
    tableSelectionChanged(rows) {

      this.selectedNodes = rows
    },
    TranspondImgClose() {
      if (this.imgSending !== 1) {
        //是否取消发送
        this.$emit('TranspondImgClose', '')
      } else {
        this.cancelSendShow = true
      }

    },
    cancelSendSure() {
      if (!this.loading) {
        this.loading = this.$loading({
          lock: true,
          text: '取消中...',
          spinner: 'el-icon-loading',
        });
      }
      this.canceled = true
      this.cancelSendShow = false
      this.imgSending = 2

    },
    sendFn() {


      this.totalCount = this.TranspondDatas.reduce((a, b) => {
        return a + b.images_count
      }, 0)
      let emptyItem = this.TranspondDatas.find(e => e.images_count === 0)
      if (!!emptyItem) {


        this.$message({
          type: 'error',
          message: `患者编号为：【${emptyItem.patient_id}】的【${emptyItem.accession_number}】检查 没有需要发送的影像`
        })
        return

      }
      // if (this.totalCount === 0) {
      //   this.$message({
      //     type: 'warning',
      //     message: '没有需要发送的影像'
      //   })
      //   return
      // }
      this.timeId = null
      this.canceled = false
      this.imgSending = 1
      this.sendImgFn(0)


    },
    sendImgFn(index) {
      if (this.canceled) return
      this.percentage = 0
      this.routingnode = this.selectedNodes[index];
      if (!this.routingnode) {
        this.$message({
          type: 'warning',
          message: '请选择目标节点'
        })
        return
      }
      this.sendImg(index)
    },

    async sendImg(index) {
      if (this.canceled) return
      // this.imgSending = 1;

      let idArr = this.TranspondDatas.map(ele => ele['id'])
      let [res, err] = await this.$pacsApi.pacsApi.sendImg(idArr, this.routingnode.id)
      if (err) {

        let error_msg = err.response ? err.response.status : '未知错误'
        this.failData = this.failData.concat(this.TranspondDatas.map(ele => ({ ...this.routingnode, ...ele, error_msg, })))
        console.log('错误信息不显示吗', err, err.response.message, this.failData);

        index++
        if (index < this.selectedNodes.length) {
          this.sendImgFn(index)
        } else {
          this.imgSending = 2;
        }

        return
      }

      let { code, msg } = res
      if (code === 0) {
        // this.$message({
        //   type: 'success',
        //   message: msg
        // })
        this.currentData = res.data
        this.msgCount = 0
        this.timeId = null
        this.pollingGetSendProgressRate(index);// 开始轮询
      } else {
        this.failData = this.failData.concat(this.TranspondDatas.map(ele => ({ ...this.routingnode, ...ele, error_msg: msg })))

      }
    },

    async getRoutingNodes() {
      let res = await this.$pacsApi.pacsApi.getRoutingNodes()
      let { code, data } = res
      if (code === 0) {
        this.routingNodes = data
      }
    },

    pollingGetSendProgressRate(index) { // 轮询获取影像发送进度
      if (this.canceled && !this.timeId) {
        this.loading.close()
        this.loading = null
        return
      }
      if (this.timeId) { // 目前有进行中的定时任务
        // 清除定时器
        clearInterval(this.timeId)
      } else {

        this.timeId = setInterval(async () => {
          // if (this.canceled) {
          //   clearInterval(this.timeId)
          // }

          let [res, err] = await this.$pacsApi.pacsApi.getSendProgressRate(this.currentData)

          if (err) {
            // this.$message({
            //   type: 'error',
            //   message: err,
            // })
            let error_msg = err.response ? err.response.status : '未知错误'
            this.failData = this.failData.concat(this.TranspondDatas.map(ele => ({ ...this.routingnode, ...ele, error_msg, })))
            index++
            if (index < this.selectedNodes.length) {
              this.sendImgFn(index)
            }
            if (index === this.selectedNodes.length) {
              this.imgSending = 2
            }
            //清除定时器
            clearInterval(this.timeId)
            return
          }

          let { code, data } = res
          if (code === 0) {
            this.completeCount = data.complete_count
            // data.task_infos.filter(e => e.task_state !== 1).reduce((a, b) => { return a + b.images_count }, 0)
            this.totalCount = data.total_count
            this.percentage = Math.floor((this.completeCount / this.totalCount) * 100)
            if (data.task_infos.length > 0) {
              //task_state==1是还在进行中
              //节点不通或者连接被拒绝，本次可以直接中断，直接下一次
              let isRefusedItem = data.task_infos.find(e => e.task_state === 3 && this.refusedReasons.includes(e.error_msg))
              let shouldNext = !!isRefusedItem || (data.task_infos.length === this.TranspondDatas.length) && !data.task_infos.some(e => e.task_state === 1)
              console.log('找不到item', isRefusedItem, !!isRefusedItem, shouldNext);

              if (shouldNext) {
                data.task_infos.forEach(element => {
                  let item = this.TranspondDatas.find(e => e.patient_id === element.patient_id && e.accession_number === element.accession_number)
                  if (element.task_state === 2) {
                    this.successData.push(Object.assign({ ...item, ...this.routingnode }, element))
                  } else {
                    if (!!isRefusedItem) {
                      element.error_msg = isRefusedItem.error_msg
                      this.failData.push(Object.assign({ ...item, ...this.routingnode }, element))
                    } else {
                      this.failData.push(Object.assign({ ...item, ...this.routingnode }, element))
                    }
                  }
                });
                clearInterval(this.timeId) //清除定时器

                // index++
                //   if (index < this.selectedNodes.length) {
                //     this.sendImgFn(index)
                //   } else {
                //     this.imgSending = 2
                //   }
                // if (this.canceled) {
                //   this.loading.close()
                //   this.loading = null
                // } 


                if (this.canceled) {
                  this.loading.close()
                  this.loading = null
                } else {
                  index++
                  if (index < this.selectedNodes.length) {
                    this.sendImgFn(index)
                  } else {
                    this.imgSending = 2
                  }
                }


              }


            }


            // if (data.total_count === -1) { // 没有进行中的任务，返回-1
            //   this.completeCount = 0
            //   this.totalCount = 0
            //   clearInterval(this.timeId) // 清除定时器
            // } else {

            // }
            // if (this.percentage === 100) {
            //   clearInterval(this.timeId) // 清除定时器
            //   this.successData = this.successData.concat(this.TranspondDatas.map(ele => ({ ...this.routingnode, ...ele })))
            //   if (index < this.selectedNodes.length-1) {
            //     this.sendImgFn(index++)
            //   } else {
            //     this.imgSending = 2
            //   }
            // }else if((this.percentage === 0 && this.msgCount>5)||data.total_count===0){
            //   clearInterval(this.timeId) 
            //   if (index < this.selectedNodes.length-1) {
            //     this.sendImgFn(index++)
            //   } else {
            //     this.imgSending = 2
            //   }
            //   let reason = (data.total_count===0 )? '检查数据异常': '节点不通'
            //   this.failData = this.failData.concat(this.TranspondDatas.map(ele => ({ ...this.routingnode, ...ele, reason })))

            // }

          }
        }, 3000)
      }
    }

  },
  mounted() {
    this.getRoutingNodes()
    // this.TranspondDatas.map(e=>{

    // })
    // this.pollingGetSendProgressRate()
  },

  components: {
    CommonTable,
    // SearchTime,
    // SendImg
  }
}
</script>
